package com.leyou.item.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.enums.ExceptionEnums;
import com.leyou.common.exception.LyException;
import com.leyou.common.vo.PageResult;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.pojo.Brand;
import com.leyou.item.service.BrandService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * 平牌管理
 */
@Service
public class BrandServiceImpl implements BrandService {

    @Autowired
    private BrandMapper brandMapper;

    @Override
    public PageResult<Brand> queryBrandByPage(Integer page,
                                              Integer rows,
                                              String sortBy,
                                              Boolean desc,
                                              String key) {

        //分页
        //使用分页插件
        PageHelper.startPage(page, rows);
        //过滤根据key条件
        /**
         * SELECT *
         * FROM tb_brand
         * WHERE NAME LIKE "%*%" OR letter ="X"
         * ORDER BY id DESC;
         */
        Example example = new Example(Brand.class);
        if (StringUtils.isNotBlank(key)) {
            //有过滤条件
            example.createCriteria().orLike("name", "%" + key + "%")
                    .orEqualTo("letter", key.toUpperCase());
        }
        //排序
        if (StringUtils.isNotBlank(sortBy)) {
            String orderByClause = sortBy + (desc == true ? " DESC" : " ASC");
            example.setOrderByClause(orderByClause);
        }
        //查询
        List<Brand> brands = brandMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(brands)) {
            throw new LyException(ExceptionEnums.BRAND_NOT_FOUND);
        }
        //解析分页结果
        PageInfo<Brand> pageInfo = new PageInfo<>(brands);

        return new PageResult<Brand>(pageInfo.getTotal(), brands);
    }

    /**
     * 新增品牌
     *
     * @param brand
     * @param cids
     */
    @Override
    @Transactional  //加事务，失败就回滚
    public void saveBrand(Brand brand, List<Long> cids) {
        brand.setId(null);//id设置了自增，这个可以不设置
        int count = brandMapper.insert(brand);
        if (count != 1) {
            throw new LyException(ExceptionEnums.BRAND_SAVE_ERROR);
        }
        //新增中间表（因为是多对多关系）
        for (Long cid : cids) {

            count = brandMapper.insertCategoryBrand(cid, brand.getId());
            if (count != 1) {
                throw new LyException(ExceptionEnums.BRAND_SAVE_ERROR);
            }
        }

    }


    public Brand queryById(Long id) {

        Brand brand = brandMapper.selectByPrimaryKey(id);
        if (brand == null) {
            throw new LyException(ExceptionEnums.GOODS_NOT_FOND);
        }

        return brand;

    }

    /**
     * 查询当前分类下的所有品牌
     *
     * @param cid
     * @return
     */
    @Override
    public List<Brand> queryBrandByCid(Long cid) {

        List<Brand> brands = brandMapper.queryByCategoryId(cid);


        return brands;
    }

    @Override
    public List<Brand> queryByIds(List<Long> ids) {

        List<Brand> brands = brandMapper.selectByIdList(ids);
        if (CollectionUtils.isEmpty(brands)) {
            throw new LyException(ExceptionEnums.BRAND_NOT_FOUND);
        }
        return brands;
    }


}
